﻿using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
using System.Web.Mvc;
using Microsoft.Practices.Unity;
using WebShop.Contracts;
using WebShop.DAL.Interfaces;
using WebShop.Infrastructure;
using WebShop.Models;

namespace WebShop.Controllers
{
    //[SessionState(System.Web.SessionState.SessionStateBehavior.Disabled)]
    [HandleErrors]
    public class CategoriesController : Controller
    {
        [Dependency]
        public ICategoryRepository Categories { get; set; }

        private const string GetImageAction = "Image";


        protected override ITempDataProvider CreateTempDataProvider()
        {
            return new CookieTempDataProvider(HttpContext);
        }

        //
        // GET: /Category/

        public ViewResult Index()
        {
            return View(Categories.List());
        }

        //
        // GET: /Category/Details/5

        /*public ViewResult Details(int id)
        {
            Category category = Categories.Get(id);

            return View(category);
        }*/

        //
        // GET: /Category/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Category/Create

        [HttpPost]
        [ValidateInput(true)]
        [ValidateAntiForgeryToken]
        public ActionResult Create([ImageBinder(FieldName = "Picture")]Category category)
        {
            if (ModelState.IsValid)
            {
                Categories.Create(category);
                Categories.SaveChanges();

                return RedirectToAction("Index");
            }

            return View(category);
        }

        //
        // GET: /Category/Edit/5

        public ActionResult Edit(int id)
        {
            Category category = Categories.Get(id);

            return View(category);
        }

        //
        // POST: /Category/Edit/5

        [HttpPost]
        [ValidateInput(true)]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Category category)
        {
            /////Удаляет картинку, если картинку не выбрали
            if (ModelState.IsValid)
            {
                var cat = Categories.Find(c=>c.CategoryID == category.CategoryID);
                if (Binders[typeof(Category)] == null) Binders.Add(typeof(Category), new ImageModelBinder("Image"));

                Categories.Edit(category);
                Categories.SaveChanges();
                var controllerName = this.ValueProvider.GetValue("controller").RawValue.ToString();
                HttpResponse.RemoveOutputCacheItem("/" + controllerName + "/" + GetImageAction + "/" + category.CategoryID);
                return RedirectToAction("Index");
            }

            return View(category);
        }

        //
        // GET: /Category/Delete/5

        public ActionResult Delete(int id)
        {
            Category category = Categories.Get(id);
            return View(category);
        }

        //
        // POST: /Category/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            Categories.Delete(id);
            Categories.SaveChanges();

            return RedirectToAction("Index");
        }

        //
        // GET: /Category/Image/5

        [HttpGet, ActionName(GetImageAction)]
        [OutputCache(CacheProfile = "CategoryImages")]
        public FileResult GetImage(int id)
        {
            Category product = Categories.Get(id);

            MemoryStream stream;

            if (product != null && product.Picture != null)
            {
                stream = new MemoryStream(product.Picture);
                //stream.Position = OleHeaderLength;
            }
            else // If product cannot be found or product doesn't have a picture
            {
                stream = new MemoryStream();

                var path = Server.MapPath(Url.DefaultCategoryImage());
                var image = new Bitmap(path);

                image.Save(stream, ImageFormat.Jpeg);
                stream.Seek(0, SeekOrigin.Begin);
            }

            return new FileStreamResult(stream, "image/jpg");
        }

        protected override void Dispose(bool disposing)
        {
            //db.Dispose();
            base.Dispose(disposing);
        }
    }
}